package com.reliable.framework.security.filter;

import com.reliable.api.dto.user.ReliableUserLite;
import com.reliable.framework.utils.JwtUtils;
import com.reliable.framework.utils.TokenContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


@Component
public class XssJwtAuthenticationFilter extends OncePerRequestFilter {



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            String path = request.getRequestURI();
            if (!path.startsWith("/reliable")) {
                filterChain.doFilter(request, response);
                return;
            }

            String token = extractToken(request);
            if (token != null && !JwtUtils.isTokenExpired(token)) {
                ReliableUserLite user = JwtUtils.parseUserFromToken(token);
                if (user != null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            user.getAccount(), null, new ArrayList<>()
                    );
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    TokenContext.setToken(token);
                }
            }

            filterChain.doFilter(request, response);
        } finally {
            SecurityContextHolder.clearContext();
            TokenContext.clear();
        }
    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken == null) {
            return null;
        }
        bearerToken = bearerToken.trim();
        if (bearerToken.toLowerCase().startsWith("bearer ")) {
            if (bearerToken.length() > 7) {
                return bearerToken.substring(7).trim();
            } else {
                return null; // token 格式不完整
            }
        }
        return null;
    }


}